//
//  AppDelegate.m
//  MuYing
//
//  Created by tbb on 2019/7/18.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import "YQMYTabBarBaseViewController.h"
#import "YQMYBaseNavigationController.h"
#import "MYLoginVC.h"
#import <AlipaySDK/AlipaySDK.h>
#import "AppDelegate+third.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>

//bestbox
#define WechatAppID @"wx38be6f1e3c5f816c"
#define WECHAT_APP_SERECET  @"679609bf4975bddc3dd6133cea3521ac"
#define UNIVERSAL_LINK @"https://bestbox.store/app/"
//香港3C
//#define WechatAppID @"wxc664eb446ba2c77b"
//#define WECHAT_APP_SERECET  @"8e6822e9466de97ff50976ba107f6f9a"
//#define UNIVERSAL_LINK @"https://bestbox.io/app/"
@interface AppDelegate ()

@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    //在register之前打开log, 后续可以根据log排查问题
    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
        NSLog(@"WeChatSDK: %@", log);
    }];
     [WXApi registerApp:WechatAppID universalLink:UNIVERSAL_LINK];
    //调用自检函数
    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult* result) {
        NSLog(@"%@, %u, %@, %@", @(step), result.success, result.errorInfo, result.suggestion);
    }];
   
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    self.window.backgroundColor = UIColor.whiteColor;
    
//    MYLoginVC *loginVC = [[MYLoginVC alloc] init];
//    YQMYBaseNavigationController *nav = [[YQMYBaseNavigationController alloc] initWithRootViewController:loginVC];
    
    YQMYTabBarBaseViewController *tabBarVC = [[YQMYTabBarBaseViewController alloc] init];
    YQPLoginModel *account = [YQPUserTool account];
//    if (account.token) {
        self.window.rootViewController = tabBarVC;
//    }else{
//        self.window.rootViewController = nav;//tabBarVC;
//    }
    [self setNavBarAppearence];
    [self.window makeKeyAndVisible];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    // 控制整个功能是否启用。
    manager.enable = YES;
    // 点击屏幕隐藏键盘
    manager.shouldResignOnTouchOutside = YES;
    // 键盘覆盖输入框时候页面自动上移
    // manager.keyboardDistanceFromTextField = 100;
    // 控制键盘上的工具条文字颜色是否用户自定义
    //manager.shouldToolbarUsesTextFieldTintColor = YES;
    // 为键盘添加工具栏
    manager.enableAutoToolbar = NO;
    // 最新版的设置键盘的returnKey的关键字 ,可以点击键盘上的next键，自动跳转到下一个输入框，最后一个输入框点击完成，自动收起键盘。
    //    manager.toolbarManageBehaviour = IQAutoToolbarByTag;
    //    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = NO;
    //解决用YYTextView，IQKeyboardManager失效问题
    [[IQKeyboardManager sharedManager]registerTextFieldViewClass:[YYTextView class]
                                 didBeginEditingNotificationName:YYTextViewTextDidBeginEditingNotification
                                   didEndEditingNotificationName:YYTextViewTextDidEndEditingNotification];
    [self thirdShare];
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)setNavBarAppearence
{
    
    UIColor *mainNavBarColor = UIColor.whiteColor;//[UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
    
    
    // 设置是 广泛使用WRNavigationBar，还是局部使用WRNavigationBar，目前默认是广泛使用
    [WRNavigationBar wr_widely];
    //黑名单
    /*
    [WRNavigationBar wr_setBlacklist:@[@"SpecialController",
                                       @"TZPhotoPickerController",
                                       @"TZGifPhotoPreviewController",
                                       @"TZAlbumPickerController",
                                       @"TZPhotoPreviewController",
                                       @"TZVideoPlayerController"]];
    */
//        NSDictionary *dic = @{ NSFontAttributeName:font,NSForegroundColorAttributeName:kAPPMainTitleColor};
    
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:mainNavBarColor];
    // 设置导航栏所有按钮的默认颜色
    [WRNavigationBar wr_setDefaultNavBarTintColor:kAPPMainTitleColor];
    // 设置导航栏标题默认颜色
    [WRNavigationBar wr_setDefaultNavBarTitleColor:kAPPMainTitleColor];
    // 统一设置状态栏样式
    //[WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
    // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
//    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey] ]; // Add any custom logic here.
//    [WXApi handleOpenURL:url delegate:self];
//    return handled;
//}

- (BOOL)application:(UIApplication*)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        [MBProgressHUD showActivityMessage:kYQLS(@"登录中...")];
         SendAuthResp *newResp= (SendAuthResp *)resp;
            NSString *newUrl=@"/api/wLogin";
            NSMutableDictionary *newParameters=[NSMutableDictionary dictionary];
            [newParameters setObject:newResp.code forKey:@"code"];
            [YQPNetWorkingManager sendPostRequest:newUrl parameters:newParameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
                [MBProgressHUD hideHUD];
                if (responseObject.code == 0) {
                    YQPLoginModel *account = [YQPLoginModel AccountStatusWithDict:responseObject.data];
                    [YQPUserTool saveAccount:account];
                    YQMYTabBarBaseViewController *tabBarVC = [[YQMYTabBarBaseViewController alloc] init];
                   self.window.rootViewController = tabBarVC;
                }
                else
                {
                    [MBProgressHUD showError:responseObject.msg];
                }
            } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
               [MBProgressHUD hideHUD];
                [MBProgressHUD showError:error];
            }];
    }
    if([resp isKindOfClass:[PayResp class]])//微信支付
    {
        switch (resp.errCode)
        {
            case WXSuccess:
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:YJPaySucceedNotiKey object:self userInfo:nil];
            }
                break;
            case WXErrCodeUserCancel:
            {
                 MBErrHUD(@"支付已取消");
            }
                break;
            default:
            {
               MBErrHUD(resp.errStr);
            }
                break;
        }
        
    }
}

@end
